package com.kgc.scd.delay;

import com.kgc.scd.service.OrderService;
import com.kgc.scd.util.RedisUtils;
import com.kgc.scd.vo.ShopOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * Created On : 2022/11/22.
 * <p>
 * Author : Administrator
 * <p>
 * Description: OrderDelay
 */
@Slf4j
public class OrderDelay implements Delayed{
    private String orderId;
    private long start=0;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisUtils redisUtils;


    public OrderDelay(String orderId, long delayInMilliseconds){
        this.orderId = orderId;
        this.start = System.currentTimeMillis() + delayInMilliseconds;
    }

    /*getDelay 用于判断任务是否到期，如果是返回-1 表示任务已经到期*/
    @Override
    public long getDelay(TimeUnit unit) {
        long diff = this.start - System.currentTimeMillis();
//        返回距离你自定义的超时时间还有多少，延迟剩余时间,单位unit指定
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int)(this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    /*模拟处理状态为已提交未支付的订单*/
    public String orderHandle(){
        log.info("系统在" + LocalDateTime.now() +"---处理延时任务---判断该订单:{}是否支付---" , orderId);

        return orderId;

    }

}
